import { ref, onMounted, onUnmounted, type Ref } from 'vue'

export interface LazyImageOptions {
  rootMargin?: string
  threshold?: number
  placeholder?: string
}

export function useLazyImage(
  imageRef: Ref<HTMLImageElement | null>,
  src: string,
  options: LazyImageOptions = {}
) {
  const isLoaded = ref(false)
  const isLoading = ref(false)
  const hasError = ref(false)
  
  const {
    rootMargin = '50px',
    threshold = 0.1,
    placeholder = ''
  } = options

  let observer: IntersectionObserver | null = null

  const loadImage = () => {
    if (!imageRef.value || isLoaded.value || isLoading.value) return

    isLoading.value = true
    hasError.value = false

    const img = new Image()
    
    img.onload = () => {
      if (imageRef.value) {
        imageRef.value.src = src
        isLoaded.value = true
        isLoading.value = false
      }
    }

    img.onerror = () => {
      hasError.value = true
      isLoading.value = false
      if (imageRef.value) {
        // 设置错误占位图
        imageRef.value.src = ''
      }
    }

    img.src = src
  }

  const setupObserver = () => {
    if (!imageRef.value || !('IntersectionObserver' in window)) {
      // 如果不支持 IntersectionObserver，直接加载图片
      loadImage()
      return
    }

    observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            loadImage()
            observer?.unobserve(entry.target)
          }
        })
      },
      {
        rootMargin,
        threshold
      }
    )

    observer.observe(imageRef.value)
  }

  onMounted(() => {
    if (imageRef.value) {
      // 设置初始占位图
      imageRef.value.src = placeholder
      setupObserver()
    }
  })

  onUnmounted(() => {
    if (observer && imageRef.value) {
      observer.unobserve(imageRef.value)
      observer.disconnect()
    }
  })

  return {
    isLoaded,
    isLoading,
    hasError,
    loadImage
  }
}